package com.csist.server;

import javax.swing.text.html.HTMLDocument;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
import java.util.Iterator;

/**
 * 服务器端线程类
 * 
 * 
 * @author csist-jf-student
 *
 */
public class ServerThread extends Thread{

	private Socket socket;
	private boolean state=true;
	private DataInputStream dis=null;
	private DataOutputStream dos=null;
		
	
	
	public ServerThread(Socket socket) {
			this.socket=socket;
			send();
	}
	
	@Override
	public void run() {
			while(this.state){
				receive();
			}
	}	
	
	/**
	 * 接收消息
	 */
	public void receive() {
		try {
			dis=new DataInputStream(this.socket.getInputStream());
			String message=dis.readUTF();
			makeInfo(message);
			
		} catch(EOFException e){ 
			close();
		} catch (IOException e) {
			close();
			e.printStackTrace();
		}
	}	
	
	/**
	 * 处理消息以便将接收消息发送客户端
	 * @param msg
	 */
	public  void  makeInfo(String msg) {
		//保证线程同步
		//建议使用迭代器删除元素
		for(Socket s:ChatServer.sockets) {
			String obj="";
			String message=msg;
			if("886".equals(msg)) {
				if(this.socket==s) {
					message="欢迎下次光临...";
				}
				else{					
					message="客户端离开聊天室";
				}
			}
			else {
				if(this.socket==s) {
					obj="我：";
				}
				else {
					obj="客户端:";
				}
			}
			try {
				dos=new DataOutputStream(s.getOutputStream());
				dos.writeUTF(obj+message);
				dos.flush();
				if("886".equals(msg)&&this.socket==s){
					ChatServer.sockets.remove(this.socket);
					close();
					if(ChatServer.sockets.size()==0){
						break;
					}
				}
			} catch (IOException e) {
				close();
				e.printStackTrace();
			}
		}
		
	}
	
	/**
	 * 发送消息
	 */
	public void send(){
		try {
			for(Socket s:ChatServer.sockets) {
				dos=new DataOutputStream(s.getOutputStream());
				String msg=(s==this.socket?"欢迎进入聊天室":"欢迎客户端进入聊天室...");
				dos.writeUTF(msg);
			}
		} catch (IOException e) {
			close();
			e.printStackTrace();
		}
	}
	
	/**
	 * 释放资源
	 */
	public void close(){
		this.state=false;

		//通过索引删除
//		for (int i=0;i<ChatServer.sockets.size(); i++){
//			if (ChatServer.sockets.get(i) == this.socket){
//				ChatServer.sockets.remove(i);
//			}
//		}
		Iterator i = ChatServer.sockets.iterator();


		synchronized (ChatServer.sockets) {
			//通过迭代器删除
			while (i.hasNext()) {
				if (i.next() == this.socket)
					i.remove();
			}
		}
		//bug在此，remove方法并不能删除以object作为参数的对象，具体原因不明白，可能原因是在ChatServer.sockets中找不到this.socket,remove失败

		//解决办法：1、通过索引删除，2、通过迭代器删除
		if(dis!=null){
			try {
				dis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		if(dos!=null){
			try {
				dos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		if(socket!=null){
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
